<template>
  <el-dialog
    title="页面访问统计"
    :visible.sync="dialogVisible"
    width="900px"
    :close-on-click-modal="false"
    @close="$emit('close')"
  >
    <div class="analytics-container">
      <!-- 时间筛选 -->
      <el-card class="filter-card" shadow="never">
        <el-form :inline="true" class="filter-form">
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              @change="handleDateChange"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loadAnalyticsData">
              刷新数据
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 统计概览 -->
      <el-card class="stats-overview" shadow="never">
        <h4>总体统计</h4>
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ totalStats.total_visits }}</div>
              <div class="stat-label">总访问量</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ totalStats.today_visits }}</div>
              <div class="stat-label">今日访问</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ totalStats.yesterday_visits }}</div>
              <div class="stat-label">昨日访问</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ totalStats.total_merchants }}</div>
              <div class="stat-label">活跃商户</div>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 访问趋势图 -->
      <el-card class="chart-card" shadow="never">
        <h4>访问趋势</h4>
        <div ref="trendChart" style="height: 300px"></div>
      </el-card>

      <!-- 商户排行 -->
      <el-card class="ranking-card" shadow="never">
        <h4>商户访问排行</h4>
        <el-table
          :data="merchantStats"
          style="width: 100%"
          max-height="300"
        >
          <el-table-column type="index" label="排名" width="60" />
          <el-table-column prop="merchant.merchant_name" label="商户名称" />
          <el-table-column prop="total_visits" label="总访问量" width="100" />
          <el-table-column prop="active_days" label="活跃天数" width="100" />
          <el-table-column label="平均日访问" width="100">
            <template slot-scope="scope">
              {{ getAverageVisits(scope.row) }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    
    <div slot="footer" class="dialog-footer">
      <el-button @click="$emit('close')">关闭</el-button>
      <el-button type="primary" @click="exportAnalytics">导出统计</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getCustomerPageAnalytics } from '@/api/nfc-customer-pages'
import * as echarts from 'echarts'

export default {
  name: 'AnalyticsDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    merchantId: {
      type: [String, Number],
      default: ''
    }
  },
  data() {
    return {
      dialogVisible: false,
      dateRange: [],
      totalStats: {
        total_visits: 0,
        today_visits: 0,
        yesterday_visits: 0,
        total_merchants: 0
      },
      dailyStats: [],
      merchantStats: [],
      trendChart: null
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val) {
        this.initData()
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val)
    }
  },
  mounted() {
    this.initChart()
  },
  beforeDestroy() {
    if (this.trendChart) {
      this.trendChart.dispose()
    }
  },
  methods: {
    // 初始化数据
    initData() {
      // 默认查询最近7天
      const endDate = new Date()
      const startDate = new Date()
      startDate.setDate(startDate.getDate() - 6)
      
      this.dateRange = [
        startDate.toISOString().slice(0, 10),
        endDate.toISOString().slice(0, 10)
      ]
      
      this.loadAnalyticsData()
    },
    
    // 加载统计数据
    async loadAnalyticsData() {
      try {
        const params = {
          merchant_id: this.merchantId,
          start_date: this.dateRange[0],
          end_date: this.dateRange[1]
        }
        
        const res = await getCustomerPageAnalytics(params)
        if (res.code === 200) {
          this.totalStats = res.data.total_stats || {}
          this.dailyStats = res.data.daily_stats || []
          this.merchantStats = res.data.merchant_stats || []
          
          this.updateChart()
        } else {
          this.$message.error(res.message || '加载统计数据失败')
        }
      } catch (error) {
        console.error('加载统计数据失败:', error)
        this.$message.error('加载统计数据失败')
      }
    },
    
    // 初始化图表
    initChart() {
      this.$nextTick(() => {
        if (this.$refs.trendChart) {
          this.trendChart = echarts.init(this.$refs.trendChart)
          this.updateChart()
        }
      })
    },
    
    // 更新图表
    updateChart() {
      if (!this.trendChart) return
      
      // 处理数据
      const dates = []
      const visits = []
      
      this.dailyStats.forEach(item => {
        dates.push(item.date)
        visits.push(item.count)
      })
      
      const option = {
        title: {
          text: '访问趋势',
          left: 'center',
          textStyle: {
            fontSize: 14
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>访问量: {c}'
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '访问量'
        },
        series: [
          {
            name: '访问量',
            type: 'line',
            smooth: true,
            data: visits,
            itemStyle: {
              color: '#409EFF'
            },
            areaStyle: {
              color: 'rgba(64, 158, 255, 0.1)'
            }
          }
        ],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          containLabel: true
        }
      }
      
      this.trendChart.setOption(option)
    },
    
    // 时间范围变化
    handleDateChange(dates) {
      this.dateRange = dates
      if (dates && dates.length === 2) {
        this.loadAnalyticsData()
      }
    },
    
    // 计算平均访问量
    getAverageVisits(row) {
      if (!row.active_days || row.active_days === 0) return 0
      return Math.round(row.total_visits / row.active_days)
    },
    
    // 导出统计数据
    exportAnalytics() {
      const exportData = {
        total_stats: this.totalStats,
        daily_stats: this.dailyStats,
        merchant_stats: this.merchantStats,
        date_range: this.dateRange
      }
      
      const jsonStr = JSON.stringify(exportData, null, 2)
      const blob = new Blob([jsonStr], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `页面访问统计_${this.dateRange[0]}_${this.dateRange[1]}.json`
      link.click()
      URL.revokeObjectURL(url)
      
      this.$message.success('导出成功')
    }
  }
}
</script>

<style scoped>
.analytics-container {
  max-height: 600px;
  overflow-y: auto;
}

.filter-card {
  margin-bottom: 20px;
}

.stats-overview {
  margin-bottom: 20px;
}

.stats-overview h4 {
  margin: 0 0 15px 0;
  color: #303133;
}

.stat-item {
  text-align: center;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-card h4 {
  margin: 0 0 15px 0;
  color: #303133;
}

.ranking-card h4 {
  margin: 0 0 15px 0;
  color: #303133;
}
</style>